<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-del="rowDel"
               @sort-change="sortChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               :row-class-name="rowClassName"
               :cell-class-name="rowClassName"
               @on-load="onLoad">
      <template #menu-left>
        <el-button
                type="warning"
                icon="el-icon-download"
                @click="handleExport"
        >导出
        </el-button>
        <el-button
                type="success"
                icon="Check"
                @click="handleCheck"
                v-if="permission.invoice_check_audit"
        >过账
        </el-button>
        <el-button
                type="danger"
                icon="Close"
                @click="handleUnCheck"
                v-if="permission.invoice_check_reject"
        >反过账
        </el-button>
      </template>
      <template #customerNo-search="{ disabled, size }">
        <el-autocomplete
                style="width: 100%;"
                v-model="search.customerNo"
                :fetch-suggestions="queryCustomerNo"
                placeholder="请输入Customer Code"
                :trigger-on-focus="false"
                @select="selectCustomerNo"
                :fit-input-width="true"
        ></el-autocomplete>
      </template>
      <template #customerName-search>
        <el-input v-model="search.customerName" readonly placeholder="请选择 Customer Name" @click="selectCustomerName" />
      </template>

      <template #invoiceDate-search="{ disabled, size }">
        <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.invoiceDateRange"
                type="daterange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="Invoice Date"
                @change="handleDatePickerChange"
                :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>
      <template #menu-right="{disabled}">
        <div style="float: left; padding-right: 20px;">
          <el-radio-group v-model="query.payStatus" class="list">

            <el-radio label=""  @change="refreshChange">All</el-radio>
            <el-radio label="Paid"  @change="refreshChange">Paid</el-radio>
            <el-radio label="Unpaid"  @change="refreshChange">Unpaid</el-radio>
          </el-radio-group>

        </div>
      </template>

      <template #menu="{ row, size, type }">
        <el-tooltip content="查看" placement="top">
          <el-button
                  icon="el-icon-view"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleView(row)"
                  v-if="permission.invoice_main_view"
          >
          </el-button>
        </el-tooltip>
        <!--<el-tooltip content="编辑" placement="top">-->
          <!--<el-button-->
                  <!--icon="Edit"-->
                  <!--link-->
                  <!--:size="size"-->
                  <!--:type="type"-->
                  <!--@click="() => handleEdit(row)"-->
                  <!--v-if="permission.invoice_main_edit"-->
          <!--&gt;-->
          <!--</el-button>-->
        <!--</el-tooltip>-->
        <el-tooltip content="确认发票" placement="top" v-if="row.invoiceStatus =='Draft'&& row.billCheck !='是'">
          <el-button
                  icon="EditPen"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleEdit(row)"
                  v-if="permission.invoice_main_audit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="反审核" placement="top" v-if="row.invoiceStatus =='Confirmed' && row.billCheck !='是'">
          <el-button
                  icon="NoSmoking"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rollbackAudit(row)"
                  v-if="permission.invoice_main_audit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="已付款" placement="top" v-if="row.invoiceStatus =='Confirmed' && row.payStatus == 'Unpaid'">
          <el-button
                  icon="Money"
                  link
                  :size="size"
                  :type="type"
                  @click="() => changePayStatus(row,1)"
                  v-if="permission.invoice_main_pay"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="取消付款" placement="top" v-if="row.invoiceStatus =='Confirmed' && row.payStatus == 'Paid'">
          <el-button
                  icon="Suitcase"
                  link
                  :size="size"
                  :type="type"
                  @click="() => changePayStatus(row,2)"
                  v-if="permission.invoice_main_pay"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="发票报表" placement="top">
          <el-button
                  icon="Reading"
                  link
                  :size="size"
                  :type="type"
                  @click="() => showChoice(row)"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="修正查询" placement="top">
          <el-button
                  icon="List"
                  link
                  :size="size"
                  :type="type"
                  @click="() => showLog(row)"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top" v-if="row.invoiceStatus =='Draft'">
          <el-button
                  icon="el-icon-delete"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rowDel(row)"
                  v-if="permission.invoice_main_delete"
          >
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <select-customer  ref="selectCustomer"  @success="setCustomerNo"/>
    <invoice-form ref="invoiceForm" @success="refreshChange"/>
    <invoice-log ref="invoiceLog" />
  </basic-container>
</template>

<script>
  import {getList, getDetail, remove,invoiceReport,changeStatus, changePayStatus,billCheckByIds, unBillCheckByIds} from "@/api/anwise/invoice/invoice_main";
  import {changeBillStatus} from "@/api/anwise/invoice/invoice_main";
  import invoiceForm from './components/invoice_form.vue';
  import {remoteList} from '@/api/anwise/customer/customer';
  import selectCustomer from '../order/components/select_customer.vue';
  import invoiceLog from './components/invoice_log.vue';
  import {Pattern} from "@/utils/validate.js";
  import {calcDate, dateFormat} from "@/utils/date.js";
  import {mapGetters} from "vuex";
  import { getToken } from '@/utils/auth';
  import { exportBlobPost } from '@/api/common';
  import { downloadXls } from '@/utils/util';
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';

  export default {
    components: {
      selectCustomer,
      invoiceForm,
      invoiceLog
    },
    data() {
      return {
        form: {},
        query: {},
          search:{},
          invoiceDateRange:[],
          pickerOptions:[],
          dateFormat:"YYYY-MM-DD",
          loading: true,
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
            height:'auto',
            calcHeight: 30,
            tip: false,
            searchShow: false,
            searchMenuSpan: 6,
            border: true,
            index: true,
            selection: true,
            reserveSelection:true,
            labelWidth: 150,
            searchLabelWidth: 160,
            indexWidth:100,
            menuWidth: 230,
            addBtn: false,
            editBtn: false,
            viewBtn: false,
            delBtn: false,
            stripe: true,
            searchIndex: 3,
            searchIcon: false,
            searchEnter:true,
          column: [
              {
                  label: "Invoice Date",
                  prop: "invoiceDate",
                  type: "input",
                  fixed: true,
                  search:true,
                  overHidden: true,
                  sortable: true,
                  width:140,
              },
            {
              label: "Invoice No.",
              prop: "invNo",
              type: "input",
              search: true,
                fixed: true,
                overHidden: true,
                sortable: true,
                width:140,
            },
            {
              label: "Posted",
              prop: "billCheck",
              type: "select",
              search: true,
              dicUrl: "/blade-system/dict-biz/dictionary?code=biz_yes_no",
              filterable: true,
              props: {
                label: 'dictValue',
                value: 'dictKey',
              },
              value:'是',
              dataType: 'string',
              fixed: true,
              overHidden: true,
              sortable: true,
              width:140,
            },
              {
                  label: "Supplier",
                  prop: "companyName",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:140,
              },
              {
              label: "Customer Code",
              prop: "customerNo",
              type: "input",
              search: true,
                  overHidden: true,
                  sortable: true,
                  width:160,
            },
            {
              label: "Customer Name",
              prop: "customerName",
              type: "input",
              search: true,
                overHidden: true,
                sortable: true,
                width:170,
            },
              {
                  label: "Invoice ref.",
                  prop: "kdInvoiceNo",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:140,
              },
              {
              label: "Payment Terms",
              prop: "paymentTerms",
              type: "input",
                  overHidden: true,
                  sortable: true,
                  width:160,
            },
              {
                  label: "Due Date",
                  prop: "dueDate",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:140,
                  html:true,
                  formatter:(row,value,label)=>{
                      let days =  this.calcAgingDate(row);
                      if (days== '-') {
                          return value;
                      } else {
                          return '<span style="color:#ff4542">'+value+'</span>'
                      }
                  },
              },
              {
                  label: "Aging (Days)",
                  prop: "delayDays",
                  type: "input",
                  overHidden: true,
                  // sortable: true,
                  width:150,
                  html:true,
                  formatter:(row,value,label)=>{
                      let days =  this.calcAgingDate(row);
                      if (days== '-') {
                          return days;
                      } else {
                          return '<span style="color:#ff4542">'+days+'</span>'
                      }
                  },
              },
              {
                  label: "Currency",
                  prop: "currency",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:140,
              },
              {
                  label: "Invoice Amount",
                  prop: "invoiceAmount",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:160,
                  formatter:(row,value,label)=>{
                      return this.currencyFilter(value);
                    }
                  },
              {
                  label: "Payment Status",
                  prop: "payStatus",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:160,
              },
              // {
              //     label: "Status",
              //     prop: "invoiceStatus",
              //     type: "input",
              //     overHidden: true,
              //     sortable: true,
              //     search:true,
              //     width:140,
              // },
            {
              label: "Status",
              prop: "invoiceStatus",
              type: "select",
              search: true,
              dicUrl: "/blade-system/dict-biz/dictionary?code=invoice_status",
              filterable: true,
              props: {
                label: 'dictValue',
                value: 'dictKey',
              },
              dataType: 'string',
              overHidden: true,
              sortable: true,
              width:140,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.invoice_main_add, false),
          viewBtn: this.validData(this.permission.invoice_main_view, false),
          delBtn: this.validData(this.permission.invoice_main_delete, false),
          editBtn: this.validData(this.permission.invoice_main_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleCheck() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        const hasDraft = this.selectionList.some(item => item.invoiceStatus === "Draft");
        if (hasDraft) {
          this.$message.error("Draft发票不支持过账！");
          return;
        }
        billCheckByIds(this.ids).then(res=> {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: res.data.msg || "对账成功！"
            });
            this.onLoad(this.page);
          }else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
        })
      },
      handleUnCheck() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        const hasDraft = this.selectionList.some(item => item.invoiceStatus === "Draft");
          if (hasDraft) {
            this.$message.error("Draft发票不支持反过账！");
            return;
          }
        unBillCheckByIds(this.ids).then(res=> {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: res.data.msg || "反对账成功！"
            });
            this.onLoad(this.page);
          }else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
        })
      },
      showLog(row) {
        this.$refs.invoiceLog.show(row.id);
      },
        calcAgingDate(row) {
            let now = new Date().getTime();
            let date3 = now - new Date(row.dueDate).getTime();
            // console.log(row.invNo,"qqqqqq",date3,date3>0);

            let days = Math.floor(date3 / (24 * 3600 * 1000));
            if (row.payStatus === 'Paid' || days<=0) {
                return "-";
            }
            // console.log(row.invNo,"wwwww",days);
            return days;
        },
        rowClassName({row, rowindex}) {
            if (row.invoiceStatus ==='Draft') {
                return 'row-yellow';
            }
        },
        changePayStatus(row, type) {
            if(row.invoiceStatus !=='Confirmed') {
                this.$message({
                    type: "error",
                    message: "请先审核发票!"
                });
                return;
            }
            this.loading = true;
            changePayStatus(row.id, type).then(res => {
                this.loading = false;
                if (res.data.success) {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: res.msg || "操作成功!"
                    });
                }
            })
        },
        rollbackAudit(row) {
            this.loading = true;
            changeStatus(row.id, 2).then(res => {
                this.loading = false;
                if (res.data.success) {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: res.msg || "反审核成功!"
                    });
                }
            })
        },
      handleAudit(row) {
        this.loading = true;
        // changeStatus(row.id, 1).then(res => {
        //   this.loading = false;
        //   if (res.data.success) {
        //     this.onLoad(this.page);
        //     this.$message({
        //       type: "success",
        //       message: res.msg || "审核成功!"
        //     });
        //   }
        // }).catch(() => {
        //   this.loading = false;
        // });
      },
      handleView(row) {
        let title="查看发票信息";
        let type='view';
        const id = row.id;
        this.$refs.invoiceForm.show({
          id,
          title,
          type
        })
      },
      handleEdit(row) {
        let title="发票信息";
        let type='edit';
        const id = row.id;
        this.$refs.invoiceForm.show({
          id,
          title,
          type
        })
      },
      showChoice(row){
        invoiceReport(row.id, this.isEnglish,this.hiddenBom).then(res => {
          if(res.data.success) {
            const file = res.data.data;
            // const originUrl = (file.url.replace(file.domain, `${this.res}/`));
            const url = file.url;
            // this.$refs.preview.open({
            //     url: url || "",
            //     originUrl: originUrl || ""
            // });
            // console.log(url)
            window.open(`/plugins/pdfjs/web/viewer.html?file=`+url);
          }
        })
      },
      handleExport(){
        NProgress.start();
        exportBlobPost(
                `/blade-anwise/invoice/invoice_main/export?${this.website.tokenHeader
                }=${getToken()}`, this.query
        ).then(res => {
          downloadXls(res.data, `发票列表${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
          NProgress.done();
        });
      },
      setCustomerNo(row) {
          this.search.customerName = "";
          if (row) {
              this.search.customerId = row.id;
              this.search.customerNo = row.custNo;
              this.search.customerName = row.custName;}
      },
      selectCustomerName() {
          this.$refs.selectCustomer.showSelect();
      },

      queryCustomerNo(val,cb) {
          this.search.customerName = "";
          const reg = Pattern.number;
          // console.log(reg.test(val));
          if (!reg.test(val)) {
              this.$message({
                  type: "error",
                  message: "客户账号只能为数字!"
              });
              return;
          }

          remoteList(val).then(res => {
              if (res.data.success) {
                  let customerList = [];
                  res.data.data.forEach(item => {
                      customerList.push({
                          value:item.custNo +" - "+item.custName,
                          customerId: item.id,
                          customerNo: item.custNo,
                          customerName: item.custName,
                      });
                  })
                  cb(customerList);
              }
          })
      },
      selectCustomerNo(item) {
          // console.log(item);
          this.search.customerId = item.customerId;
          this.search.customerNo = item.customerNo;
          this.search.customerName = item.customerName;
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
          this.invoiceDateRange = [];
          this.search.invoiceDateStart = '';
          this.search.invoiceDateEnd = '';
        this.onLoad(this.page);
      },
        sortChange(val) {
            // console.log(val)
            this.sort = {
                prop: val.prop,
                order: val.order
            };
            let order = "";
            if (this.sort.prop && this.sort.order) {
                if (this.sort.order === "descending") {
                    order = `${this.sort.prop} desc`
                } else {
                    order = `${this.sort.prop} asc`
                }
            }
            this.query.orderBy = order;
            this.onLoad(this.page);
        },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        handleDatePickerChange(value) {
            // console.log(value);
            if (value) {
                this.search.invoiceDateStart = value[0];
                this.search.invoiceDateEnd = value[1];
            } else {
                this.search.invoiceDateStart = '';
                this.search.invoiceDateEnd = '';
            }
        },
    }
  };
</script>

<style>
  .row-yellow {
    background-color: rgb(255, 253, 230) !important;
    cursor: pointer;
  }
</style>
